<?php
/**
 * User: xuanbang.wen
 * Date: 2019/12/20
 */

namespace App\Command\Tools;


use App\Service\Dict;
use EchoPHP\Console\Command;
use EchoPHP\Facades\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class GenerateDictArea extends Command {
    protected $signature = "tools:generateDictArea";
    protected $description = '生成地区json';
    protected $hotCity = ['北京', '上海', '广州', '深圳', '武汉', '西安', '杭州', '南京', '成都', '重庆', '东莞', '大连', '沈阳', '苏州', '昆明',
                          '长沙', '合肥', '宁波', '郑州', '天津', '青岛', '济南', '哈尔滨', '长春', '福州'];
    protected $jsonFilePath = '';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct() {
        parent::__construct();
    }

    /*
     * 生成过程
     */
    public function handle() {
        $this->jsonFilePath = config('app.dict_json');

        $dict = new Dict();
        $dict->setLang('zh');
        $dictZh = $dict->all('jobarea');
        $dict->setLang('en');
        $dictEn = $dict->all('jobarea');
        ksort($dictZh);
        $except = ['010000', '020000', '040000', '050000', '060000', '360000'];//直辖市和国外排除
        $hotCityArr = $allProvinceArr = [];
        foreach ($dictZh as $code => $value) {
            if (substr($code, 2, 4) == '0000' && !in_array($code, $except)) {
                $allProvinceArr [] = [
                    'label' => $value,
                    'en'    => $dictEn[$code],
                    'code'  => $code,
                    'child' => []
                ];
            }
            if (in_array($value, $this->hotCity)) {
                $hotCityArr [] = [
                    'label' => $value,
                    'en'    => $dictEn[$code],
                    'code'  => $code,
                    'child' => []
                ];
            }
        }

        foreach ($hotCityArr as &$item) {
            foreach ($dictZh as $code => $value) {
                if (in_array($item['code'], ['010000', '020000', '040000', '060000', '050000'])) {
                    if (substr($code, 0, 2) == substr($item['code'], 0, 2)) {
                        $item['child'][] = [
                            'label' => $value,
                            'en'    => $dictEn[$code],
                            'code'  => $code,
                            'child' => []
                        ];
                    }
                } else {
                    if (substr($code, 0, 4) == substr($item['code'], 0, 4)) {
                        $item['child'][] = [
                            'label' => $value,
                            'en'    => $dictEn[$code],
                            'code'  => $code,
                            'child' => []
                        ];
                    }
                }
            }
        }

        foreach ($allProvinceArr as &$province) {
            if (!in_array($province['code'], ['330000', '340000', '350000'])) {
                foreach ($dictZh as $code => $value) {
                    if (substr($code, 0, 2) == substr($province['code'], 0, 2) && substr($code, 4, 2) == '00') {
                        $province['child'][] = [
                            'label' => $value,
                            'en'    => $dictEn[$code],
                            'code'  => $code,
                            'child' => []
                        ];
                    }
                }
                foreach ($province['child'] as &$city) {
                    foreach ($dictZh as $code => $value) {
                        if (substr($code, 0, 4) == substr($city['code'], 0, 4) && $code != $city['code'] && substr($city['code'], 2, 4) != '0000') {
                            $city['child'][] = [
                                'label' => $value,
                                'en'    => $dictEn[$code],
                                'code'  => $code,
                            ];
                        }
                    }
                }
            }
        }
        $content1 = [[
                         'label' => '热门城市',
                         'en'    => '',
                         'code'  => '',
                         'child' => $hotCityArr,
                     ],
                     [
                         'label' => '所有省份',
                         'en'    => '',
                         'code'  => '',
                         'child' => $allProvinceArr,
                     ]];
        $result1 = file_put_contents($this->jsonFilePath . 'area.json', json_encode(array_values($content1), 320));

        foreach ($hotCityArr as &$city) {
            $city['child'] = [];
        }

        foreach ($allProvinceArr as &$province) {
            foreach ($province['child'] as &$city) {
                $city['child'] = [];
            }
        }
        $content1 = [[
                         'label' => '热门城市',
                         'en'    => '',
                         'code'  => '',
                         'child' => $hotCityArr,
                     ],
                     [
                         'label' => '所有省份',
                         'en'    => '',
                         'code'  => '',
                         'child' => $allProvinceArr,
                     ]];
        $result2 = file_put_contents($this->jsonFilePath . 'jobarea.json', json_encode(array_values($content1), 320));
        $this->caseTemplateAreaDict($hotCityArr, $allProvinceArr);
        if ($result1 && $result2) {
            $this->output->success('json文件生成成功');
            exit();
        }
        $this->output->error('json文件生成失败');
        exit();
    }

    private function caseTemplateAreaDict($hotCityArr, $allProvinceArr){
        try {
            $workBook = IOFactory::load(config('app.case_tempalte'));
//            $dictSheet = $workBook->getSheet(1);
            $workBook->removeSheetByIndex(1);
            $dictSheet = $workBook->createSheet(1);
            $dictSheet->setTitle('地区字典');
            $row = 1;
            $dictSheet->setCellValueByColumnAndRow(1, $row, '热门城市');
            $row++;
            foreach ($hotCityArr as $item){
                $dictSheet->setCellValueByColumnAndRow(2, $row, $item['label']);
                $dictSheet->setCellValueByColumnAndRow(3, $row, $item['code']);
                $row++;
            }
            $dictSheet->setCellValueByColumnAndRow(1, $row, '所有省份');
            $row++;
            foreach ($allProvinceArr as $province){
                $dictSheet->setCellValueByColumnAndRow(1, $row, $province['label']);
                if (empty($province['child'])){
                    $dictSheet->setCellValueByColumnAndRow(2, $row, $province['label']);
                    $dictSheet->setCellValueByColumnAndRow(3, $row, $province['code']);
                    $row++;
                }
                foreach ($province['child'] as $city){
                    $dictSheet->setCellValueByColumnAndRow(2, $row, $city['label']);
                    $dictSheet->setCellValueByColumnAndRow(3, $row, $city['code']);
                    $row++;
                }
            }
            $dictSheet->getColumnDimension('B')->setWidth(15);

            $writer = IOFactory::createWriter($workBook, 'Xlsx');
            $writer->save(config('app.case_tempalte'));
        } catch (\Exception $e) {
            $this->output->success('职位模板地区字典重写失败');
        }
    }
}